import multiprocessing
import os
import time
import shutil
from traceback import format_exc

from app.utils.index import file2base64, base2file
from app.model.request_model import Photo
from app.model.photo_standard_model import PhotoStandardConfig, PhotoStandardMode
from app.service.photo_service import PhotoService
from app.exception.base import BaseException



def make_standardized(file_path, save_dir, save_dir2):
  print("开始处理" + file_path)

  file_name = os.path.basename(file_path)
  base_name, file_ext = os.path.splitext(file_name)

  source_file = os.path.join(save_dir, file_name)
  stand_file = os.path.join(save_dir, f"{base_name}_标准化{file_ext}")
  stand_life_size_file = os.path.join(save_dir, f"{base_name}_标准化_未裁剪{file_ext}")
  stand_file2 = os.path.join(save_dir2, f"{base_name}{file_ext}")
  stand_life2_size_file = os.path.join(save_dir2, f"{base_name}_标准化_未裁剪{file_ext}")
  mark_file = os.path.join(save_dir, f"{base_name}_标注{file_ext}")
  error_file = os.path.join(save_dir, f"{base_name}__错误.txt")

  if os.path.exists(stand_file2):
    return

  try:
    # 拷贝原图
    shutil.copy(file_path, source_file)

    photo_param = Photo(base64=file2base64(file_path), config=PhotoStandardConfig(background_color="#28bef9", change_background_color=False, mode=PhotoStandardMode.AUTO))
    photo_service = PhotoService(photo=photo_param)
    # 先保存中间图
    # mark = photo_service.photo_mark()
    # base2file(mark_file, mark)
    # 标准化裁剪
    resize_img, life_img, warnning = photo_service.photo_standardized()
    if not resize_img:
      raise Exception("resize_img is empty")
    if not life_img:
      raise Exception("life_img is empty")
    base2file(stand_file, resize_img)
    base2file(stand_life_size_file, life_img)
    base2file(stand_file2, resize_img)
    # base2file(stand_life2_size_file, life_img)

  except OSError:
    error_file = os.path.join(save_dir, f"{base_name}_OSError_错误.txt")
    with open(error_file, "w") as file:
      file.write(format_exc())
  except BaseException as exc:
    error_file = os.path.join(save_dir, f"{base_name}_{exc.status_code.value}_错误.txt")
    with open(error_file, "w") as file:
      file.write(format_exc())
  except Exception as exc:
    error_file = os.path.join(save_dir, f"{base_name}_Exception_错误.txt")
    with open(error_file, "w") as file:
      file.write(format_exc())


if __name__=="__main__":
  # source_dir = r"E:\workspace\machine-learning\yolo\测试\2023年4月23日滨州职业学院-入学-137人-石志贺-原图"
  # source_dir = r"E:\workspace\machine-learning\yolo\测试\小程序原图-500"
  source_dir = r"E:\workspace\machine-learning\yolo\测试\2024-12-19_原片"

  save_dir = source_dir + "_结果"
  save_dir2 = source_dir + "_标准化"
  if not os.path.exists(save_dir):
    os.mkdir(save_dir)
  if not os.path.exists(save_dir2):
    os.mkdir(save_dir2)

  start_time = time.time()
  params = []
  # 执行代码
  for root, dirs, files in os.walk(source_dir):
    for file in files:
      file_path = os.path.join(root, file)
      p = (file_path, save_dir, save_dir2)
      params.append(p)

  print(params)
  with multiprocessing.Pool(processes=4) as pool:
    # 向进程池中添加任务
    pool.starmap(make_standardized, params)
  # for root, dirs, files in os.walk(source_dir):
  #   for file in files:
  #   index = 1
  #   total = len(files)
  #   for file in files:
  #     # if index < 185:
  #     #   index += 1
  #     #   continue
  #     print("--", index, "/", total, "--")
  #     file_path = os.path.join(root, file)
  #     make_standardized(file_path, save_dir, save_dir2)
  #     index += 1

  end_time = time.time()
  execution_time = end_time - start_time
  print(f"全部处理完毕，执行时间为：{execution_time}秒")
